<template>
  <a-card :bordered="false">
    <h3>挚友福利</h3>
    <LessFilter ref="filter" :type="2" @onAdd="handleAddOrEdit" @onSearch="onSearch"></LessFilter>

    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
      <div slot="activityState" slot-scope="text,record"><a-switch :checked="text == 1 ? true : false"  checked-children="启用" un-checked-children="禁用"  @change="onChange(record,text)" /></div>

      <span slot="action" slot-scope="record">
        <a-button class="btn" style="min-width: 90px;" @click="handleAddOrEdit(record)">编辑</a-button>
        <a-popconfirm title="确定删除挚友福利吗？" ok-text="确定" cancel-text="暂不" @confirm="handleDelete(record)">
          <a-button class="btn" style="min-width: 90px;">删除</a-button>
        </a-popconfirm>
      </span>
    </s-table>

    <a-modal :title="(eidt ? '编辑' : '新增') + '挚友福利'" :visible="visible" width="800px" @ok="modelFormOk" @cancel="visible = false">
      <a-spin :spinning="spinning" tip="加载中...">
        <a-form-model ref="editForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 4 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
          <a-form-model-item label="活动名称" prop="activityName">
            <a-input allowClear v-model.trim="form.activityName" :maxLength="16" placeholder="最多输入16字"/>
          </a-form-model-item>
          <a-form-model-item label="品牌" prop="brandId">
            <a-select v-model="form.brandId" placeholder="请选择" show-search>
              <a-select-option :value="item.id" v-for="item in brandList" :key="item.id"> {{ item.brandName }} </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="亲密值门槛" prop="closeValueFloor">
            <a-row>
              <a-col :span="6">
                <a-radio-group v-model="form.closeValueType" name="radioGroup">
                  <a-radio :value="0">不限</a-radio>
                  <a-radio :value="1">限制</a-radio>
                </a-radio-group>
              </a-col>
              <a-col :span="6">
                <a-input-number v-if="form.closeValueType == 1" id="inputNumber" v-model.trim="form.closeValueFloor" :min="0" :precision="0"/>
              </a-col>
            </a-row>
          </a-form-model-item>
          <a-form-model-item label="配置福利券" required>
            <a-list size="small" item-layout="vertical" :data-source="form.couponList">
              <a-list-item slot="renderItem" slot-scope="item, index">
                <a-row :gutter="16">
                  <a-col class="gutter-row" :span="8">
                    <a-form-model-item :prop="`couponList.${index}.awardid`" :rules="rules.awardid" style="margin-bottom: 0">
                      <a-input v-model.trim="item.awardid" style="width: 150px;" placeholder="请输入券ID"/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item :prop="`couponList.${index}.count`" :rules="rules.count" style="margin-bottom: 0">
                      每人领<a-input-number v-model.trim="item.count" :min="1" :max="100" :precision="0" style="width: 80px;" />张
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="4">
                    <a-button v-if="index != 0" class="btn" type="link" style="color: red" icon="delete" @click="deleteCoupon(index)"></a-button>
                  </a-col>
                </a-row>
              </a-list-item>
            </a-list>
            <a-button class="btn" @click="addCoupon()">添加券</a-button>
          </a-form-model-item>
          <a-form-model-item label="跳转链接">
            <a-radio-group v-model:value="form.linkType">
              <a-radio :value="1">内链</a-radio>
              <a-radio :value="2">外链</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="活动规则" v-if="form.linkType == 1">
            <JImageUpload
              :uploadParams="getUploadParams()"
              :isMove="false"
              :isMultiple="false"
              :fileSize="10"
              :number="9"
              :accept="'image/*'"
              @fileChange="fileLinkImgeUrlChange"
              v-model="linkImgeUrlList"
            ></JImageUpload>
            <div class="des">建议尺寸宽750px，上传2M以内jpg、png格式图片，最多上传9张</div>
          </a-form-model-item>
          <a-form-model-item label="链接路径" v-if="form.linkType == 2">
            <a-input v-model.trim="form.linkUrl" placeholder="请输入跳转链接路径"/>
          </a-form-model-item>
          <a-form-model-item label="外链appID" v-if="form.linkType == 2">
            <a-input v-model.trim="form.appid" placeholder="请输入外链appID"/>
          </a-form-model-item>
          <a-form-model-item label="备注">
            <a-textarea v-model.trim="form.remark" :maxLength="500" placeholder="" :rows="4" allowClear />
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>
  </a-card>
</template>
<script>
  import moment from 'moment'
import { activityInfoList, brandList, saveOrUpdateActivity, activityDetail, removeActivity,onOrOffActivity } from '@/api/marketingCenter/less'
import { STable } from '@/views/box/components'
import LessFilter from '../components/lessFilter'
  import ACol from 'ant-design-vue/es/grid/Col'
  import AListItem from 'ant-design-vue/es/list/Item'
  import ARow from 'ant-design-vue/es/grid/Row'
  import JImageUpload from '../../components/JImageUpload.vue'

  const columns = [
    {
      title: '序号',
      align: 'center',
      width: 60,
      customRender: (text, record, index) => `${index + 1}`
    },
    {
      title: '活动名称',
      dataIndex: 'activityName',
      align:"center"
    },
    {
      title: '亲密值门槛',
      dataIndex: 'closeValueFloor',
      align:"center"
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      align:"center"
    },
    {
      title: '状态',
      dataIndex: 'activityState',
      align:"center",
      scopedSlots: { customRender: 'activityState' }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align:"center",
      customRender: (text) => {
        return moment(text).format('YYYY-MM-DD')
      }
    },
    {
      title: '操作',
      width: '350px',
      align: 'center',
      fixed: 'right',
      scopedSlots: { customRender: 'action' }
    }
  ]

  const statusMap = {
    0: {
      status: 'error',
      text: '禁用'
    },
    1: {
      status: 'success',
      text: '启用'
    }
  }

export default {
  components: {
    ARow,
    AListItem,
    ACol,
    LessFilter,
    STable,
    JImageUpload
  },
  data() {
    return {
      visible: false,
      showVisible: false,
      eidt: false,
      spinning: false,
      brandList: [],
      columns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {
        "activityName": "",
        "closeValueFloor": "",
        "brandId": "",
        "activityState": "",
        "activityType": 2
      },

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
        const data = {
          "current": parameter.pageNo,
          "size": parameter.pageSize,
          ...this.queryParam
        }
        return activityInfoList(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      },

      form: {
        id: 0,
        activityName: '',
        brandId: '',
        closeValueFloor: 0,
        closeValueType: 0,
        couponList: [{
          awardid: '',
          count: 1
        }],
        linkType: 1,
        linkUrl: '',
        appid: '',
        remark: ''
      },

      rules: {
        activityName: [{ required: true, message: '请输入', trigger: 'blur' }],
        brandId: [{ required: true, message: '请选择', trigger: 'blur' }],
        awardid: [{ required: true, message: '请输入', trigger: 'blur' }]
      },

      linkImgeUrlList: [],
    }
  },
  activated() {
  },
  computed: {},
  mounted() {
    this.getBrandList()
  },
  watch: {
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    },
  },
  methods: {
    requestFlag() {
      const currentPathBase = '/marketingCenter/less/activity/welfareActivityList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },

    getBrandList() {
      brandList({
        current: 0,
        size: 99,
        state: 1
      }).then(res => {
        if (res.code === 200) {
          this.brandList = res.data.records
        } else {
          this.$message.error(res.msg || res.message)
        }
      }).catch(err => {
      })
    },

    // 删除
    handleDelete(record) {

      removeActivity({id: record.id}).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 新增编辑
    handleAddOrEdit(v) {
      if(v != 'null'){
        activityDetail({id: v.id}).then(res => {
          if (res.code === 200) {
            Object.assign(this.form, res.data);
            if(res.data.linkType == 1) {
              this.linkImgeUrlList = res.data.linkUrl.split(',')
            }
            console.log(this.linkImgeUrlList)
            this.visible = true;
            this.edit = true;
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
        })
      }else{
        Object.assign(this.form, {
          id: 0,
          activityName: '',
          brandId: '',
          closeValueFloor: 0,
          closeValueType: 0,
          couponList: [{
            awardid: '',
            count: 1
          }],
          linkType: 1,
          linkUrl: '',
          appid: '',
          remark: ''
        });

        this.linkImgeUrlList = []

        this.visible = true;
        this.edit = false;
      }
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.queryParam.activityType = 2
      this.$refs.table.refresh(true)
    },

    modelFormOk() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          const data = {
            ...this.form,
            activityType: 2,
            closeValueFloor: this.form.closeValueType == 0 ? 0 : this.form.closeValueFloor == "" ? 0 :this.form.closeValueFloor
          }
          this.spinning = true
          saveOrUpdateActivity(data).then(res => {
            if (res.code === 200) {
              this.spinning = false
              this.visible = false
              this.$refs.table.refresh(true)
            } else {
              this.spinning = false
              this.$message.error(res.msg || res.message)
            }
          }).catch(err => {
            this.spinning = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    deleteCoupon(index) {
      this.form.couponList.splice(index, 1);
    },
    addCoupon() {
      this.form.couponList.push({
        awardid: '',
        count: 1
      });
    },
    getUploadParams() {
      return {
        actionUrl: 'https://jic.jnby.com/activity/market-act/common/upload/multipart',
        headers: {
          authorization: 'authorization-text'
        },
        uploadHost: 'https://img.bzhz.jnbygroup.com/'
      }
    },
    fileLinkImgeUrlChange(list) {
      this.form.linkUrl = list.length ? list.map(item => item.url).join(',') : ''
    },
    //状态修改
    onChange(val,text){
      val.activityState = text
      onOrOffActivity({id: val.id, activityState: text}).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg || res.message)
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img {
  display: block;
  margin: 0 auto;
  width: 120px;
  height: 120px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
}
.btn{
  margin: 4px;
}
</style>
